import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mahjong/entity/Restful.dart';
import 'package:mahjong/util/DictionaryConst.dart';
import 'package:mahjong/entity/user/VerificationMode.dart';
import 'package:mahjong/util/Http.dart';

typedef _callBack = void Function(VerificationMode data);

void defaultCallback(VerificationMode data) {}

class VerificationWidget extends StatefulWidget {
  final _callBack callBack;
  VerificationWidget({this.callBack = defaultCallback});
  @override
  _VerificationWidgetState createState() => _VerificationWidgetState();
}

class _VerificationWidgetState extends State<VerificationWidget> {
  double _top = 0.0;
  double _left = 0.0;
  Random _random = Random(DateTime.now().microsecondsSinceEpoch);
  double _verificationCodeWidth;
  double _verificationCodeHeight;
  VerificationMode _verificationMode;
  Uint8List _backgrounImage;

  bool _isSuccess;

  bool _moveTag;

  Uint8List _moveImage;

  double _moveImageHeight;

  bool _loadingError = false;

  @override
  void initState() {
    super.initState();
    _moveTag = false;
    initImage();
  }

  void initImage() {
    _moveTag = false;
    _isSuccess = false;
    Http.getInstance().request<Restful>(DictionaryConst.verificationCode,
        showLoading: true, loadingMsg: "拉取验证码中...", success: (data) {
      _verificationMode = VerificationMode.fromJson(data.body);
      _verificationCodeHeight = ScreenUtil().screenHeight / 10 * 7;
      _backgrounImage =
          Base64Decoder().convert(_verificationMode.backGroundImage);
      _moveImage = Base64Decoder().convert(_verificationMode.moveImage);
      _verificationCodeWidth =
          ScreenUtil().screenHeight / 10 * 7 * _verificationMode.scale;
      _moveImageHeight = _verificationCodeHeight * 0.2;
      // 奖滑块的位置随机生成
      _top =
          _random.nextDouble() * (_verificationCodeHeight - _moveImageHeight);
      _left =
          _random.nextDouble() * (_verificationCodeWidth - _moveImageHeight);
      setState(() {});
    }, error: (data) {
      _loadingError = true;
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_loadingError) {
      Navigator.of(context).pop();
    }
    if (_verificationMode == null) {
      return SizedBox(
          width: MediaQuery.of(context).size.height / 2,
          child: Dialog(
              elevation: 0.0,
              backgroundColor: Colors.transparent,
              child: Container(
                width: MediaQuery.of(context).size.height / 2,
                height: MediaQuery.of(context).size.height / 2,
              )));
    }
    return SizedBox(
      width: _verificationCodeWidth,
      child: Dialog(
          elevation: 0.0,
          backgroundColor: Colors.transparent,
          child: Container(
            height: _verificationCodeHeight,
            width: _verificationCodeWidth,
            child: Stack(
              children: <Widget>[
                Positioned(
                  child: Container(
                    child: _backgrounImage == null
                        ? CircularProgressIndicator()
                        : Image.memory(
                            _backgrounImage,
                            fit: BoxFit.fill,
                            height: _verificationCodeHeight,
                            width: _verificationCodeWidth,
                          ),
                  ),
                ),
                Align(
                  alignment: Alignment(0, 0),
                  child: Text(
                    "拖动滑块到阴影处",
                    style: TextStyle(
                        color: Colors.white, fontSize: ScreenUtil().setSp(30)),
                  ),
                ),
                Positioned(
                  top: _top,
                  left: _left,
                  child: GestureDetector(
                    child: Container(
                        width: _moveImageHeight,
                        height: _moveImageHeight,
                        child: Stack(children: [
                          Container(
                              decoration: BoxDecoration(boxShadow: [
                                new BoxShadow(
                                    color: Color(0xFFFFFFFF).withOpacity(0.5),
                                    blurRadius: 5.0)
                              ], border: Border.all(color: Colors.green)),
                              child: _moveTag
                                  ? _isSuccess
                                      ? Icon(
                                          Icons.check_circle,
                                          color: Colors.green,
                                          size: _moveImageHeight,
                                        )
                                      : Icon(
                                          Icons.clear,
                                          color: Colors.red,
                                          size: _moveImageHeight,
                                        )
                                  : Image.memory(
                                      _moveImage,
                                      fit: BoxFit.fill,
                                      width: _moveImageHeight,
                                      height: _moveImageHeight,
                                    )),
                        ])),
                    onPanDown: (DragDownDetails e) {},
                    onPanUpdate: (DragUpdateDetails e) {
                      _left += e.delta.dx;
                      _top += e.delta.dy;
                      if (_left < 0) {
                        _left = 0;
                      } else if (_left >
                          _verificationCodeWidth - _moveImageHeight) {
                        _left = _verificationCodeWidth - _moveImageHeight;
                      }
                      if (_top < 0) {
                        _top = 0;
                      } else if (_top >
                          _verificationCodeHeight - _moveImageHeight) {
                        _top = _verificationCodeHeight - _moveImageHeight;
                      }
                      setState(() {});
                    },
                    onPanEnd: (DragEndDetails e) {
                      _verificationMode.x = _left / _verificationCodeWidth;
                      _verificationMode.y = _top / _verificationCodeHeight;
                      _verificationMode.backGroundImage = null;
                      _verificationMode.moveImage = null;
                      Http.getInstance().request<Restful>(
                          DictionaryConst.verificationCheckCode,
                          type: RequestEnum.POST,
                          data: _verificationMode.toJson(), success: (data) {
                        setState(() {
                          _moveTag = true;
                          _isSuccess = true;
                        });
                        Future.delayed(Duration(milliseconds: 500), () {
                          Navigator.pop(context);
                          widget.callBack(_verificationMode);
                        });
                      }, error: (data) {
                        setState(() {
                          _moveTag = true;
                          _isSuccess = false;
                        });
                        Future.delayed(Duration(milliseconds: 500), () {
                          initImage();
                        });
                      });
                    },
                  ),
                ),
              ],
            ),
          )),
    );
  }
}
